﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using SAASInvest.Contracts;
using System.IO;
using System.Web;

namespace SAASInvest.WebHost
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Controller" in code, svc and config file together.
    public class Controller : IController
    { 
        public void UploadFile(FileUploadStream uploadStream)
        {
            if (uploadStream.UploadStream != null && uploadStream.UploadStream.CanRead)
            {
                string fileName = uploadStream.FileName;
                string fileFullName = Path.Combine(HttpRuntime.AppDomainAppPath, @"Upload\" + fileName);
                Stream sourceStream = uploadStream.UploadStream; 
                using (FileStream targetWriter = new FileStream(fileFullName, FileMode.CreateNew, FileAccess.Write))
                {
                    const int bufferLength = 4096;
                    byte[] buffer = new byte[bufferLength];
                    int count = 0;
                    while ((count = sourceStream.Read(buffer, 0, bufferLength)) > 0)
                    {
                        targetWriter.Write(buffer, 0, count);
                    }
                    targetWriter.Close();
                }
                sourceStream.Close();
            }
        }


        public void UploadData(FileUploadData uploadData)
        {
            string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, @"Upload\" + uploadData.FileName);
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                if (uploadData.Offset < uploadData.Length)
                {
                    fs.Seek(uploadData.Offset, SeekOrigin.Begin);
                    fs.Write(uploadData.UploadData, 0, (int)uploadData.DataCount);
                }
                fs.Close();
            }
        }
    }
}
